package cn.ydt.ydt.user.webapi.service;

import cn.ydt.ydt.common.exception.YdtServiceException;
import cn.ydt.ydt.common.pojo.domain.UserJwtVO;
import cn.ydt.ydt.common.utils.IDCardsUtils;
import cn.ydt.ydt.pojo.user.dto.FamilyAddDTO;
import cn.ydt.ydt.pojo.user.dto.FamilyUpdateDTO;
import cn.ydt.ydt.user.service.IFamilyService;
import cn.ydt.ydt.user.webapi.mapper.FamilyMapper;
import cn.ydt.ydt.user.webapi.utils.SecurityContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;

import static cn.ydt.ydt.common.resful.StatusCode.BAD_REQUEST;

@DubboService
@Service
@Slf4j
public class FamilyServiceImpl implements IFamilyService {

    @Autowired
    FamilyMapper familyMapper;

    @Override
    public void add(FamilyAddDTO familyAddDTO) throws ParseException {
        UserJwtVO userInfo = SecurityContextUtils.getUserInfo();
        String userPhone = userInfo.getUserPhone();
        String userPhoneLastFour = userPhone.substring(userPhone.length() - 6);
        String familyId = "7700"+userPhoneLastFour;
        familyAddDTO.setFamilyId(familyId);
        String familyName = familyAddDTO.getFamilyName();
        String familyAddress = familyAddDTO.getFamilyAddress();
        String idNumber = familyAddDTO.getIdNumber();
        FamilyAddDTO idNumberResult = familyMapper.findByIdNumber(idNumber);

        if (idNumberResult != null){
            throw new YdtServiceException(BAD_REQUEST,"身份已经存在");
        }

        familyAddDTO.setFamilyName(familyName);
        familyAddDTO.setFamilyAddress(familyAddress);
        familyAddDTO.setIdNumber(idNumber);
        familyAddDTO.setFamilyBirthday(IDCardsUtils.getBirthday(idNumber));
        familyMapper.insert(familyAddDTO);
    }

    @Override
    public void update(FamilyUpdateDTO familyUpdateDTO) {
        String IdNumber = familyUpdateDTO.getIdNumber();

        FamilyAddDTO idNumberResult = familyMapper.findByIdNumber(IdNumber);


        if (idNumberResult != null){
            if (IdNumber == familyUpdateDTO.getIdNumber()){
                familyMapper.update(familyUpdateDTO);
                return;
            }
            throw new YdtServiceException(BAD_REQUEST,"身份已经存在");
        }

        familyMapper.update(familyUpdateDTO);
    }

    @Override
    public List<FamilyUpdateDTO> select(String familyId) {
        if (familyId == null){
            throw new YdtServiceException(BAD_REQUEST,"此家庭id不存在");
        }
        return familyMapper.selectByFamilyId(familyId);
    }
}
